package com.xinchao.common.util;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;

import org.springframework.stereotype.Service;

/**
 * 
 * <p>Title: EmailUtil</p>  
 * <p>Description: 邮件发送Util</p>  
 * @author huangf 
 * @date 2018年8月13日
 */
@Service
public class EmailUtil {

	private static final String SENDER_ADDR = "devicesupport@xinchao.com";
	private static final String SENDER_PASSWORD = "Xinchao123";
	private static final String SENDER_HOST = "smtp.xinchao.com";
	private static final String SENDER_SSL_PORT = "465";
	private static final int SENDER_PORT = 587;
	private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

	/**
	 * 【该方法在linux服务器环境测试未通过，无法正常发送邮件.@date:2018-08-30】
	 * 
	 * @param address      目标邮箱地址
	 * @param subject 邮件主题
	 * @param content 邮件内容
	 * 
	 */
	public static void sendEmilWithSSL(String content, String subject, String address) {
		 try {
	            //Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
	            //设置邮件会话参数
	            Properties props = new Properties();
	            //邮箱的发送服务器地址
	            props.setProperty("mail.smtp.host", SENDER_HOST);
	            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
	            props.setProperty("mail.smtp.socketFactory.fallback", "false");
	            //邮箱发送服务器端口,这里设置为465端口
	            props.setProperty("mail.smtp.port", SENDER_SSL_PORT);
	            props.setProperty("mail.smtp.socketFactory.port", SENDER_SSL_PORT);
	            props.put("mail.smtp.auth", "true");
	            //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
	            Session session = Session.getDefaultInstance(props, new Authenticator() {
	                protected PasswordAuthentication getPasswordAuthentication() {
	                    return new PasswordAuthentication(SENDER_ADDR, SENDER_PASSWORD);
	                }
	            });
	            //通过会话,得到一个邮件,用于发送
	            Message msg = new MimeMessage(session);
	            //设置发件人
	            msg.setFrom(new InternetAddress(MimeUtility.encodeText("新潮-梯联网平台") + "<" + SENDER_ADDR + ">"));
	            //设置收件人
	            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address, false));
	            msg.setSubject(subject);
	            //设置邮件消息
	            msg.setText(content);
	            //设置发送的日期
	            msg.setSentDate(new Date());
	            
	            //调用Transport的send方法去发送邮件
	            Transport.send(msg);
	 
	        } catch (Exception e) {
	            e.printStackTrace();
	        }

	}
	
	
	 /**
     *  发送邮件
     * @throws MessagingException 
     * @throws IOException
     */
    public static void sendMail(String content, String subject, String ...address) throws MessagingException, IOException{
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", "smtp"); // 发送邮件协议
        properties.setProperty("mail.smtp.auth", "true");
        Session session = Session.getInstance(properties);
        Message messgae = new MimeMessage(session);
		messgae.setDataHandler(new DataHandler(new ByteArrayDataSource(content, "text/html"))); // 设置邮件内容
		messgae.setFrom(new InternetAddress(MimeUtility.encodeText("新潮-梯联网平台") + "<" + SENDER_ADDR + ">")); // 设置发送人
		messgae.setSubject(subject); // 设置邮件主题
		Address[] receiverAddrs = new Address[address.length];
		for(int i =0; i < address.length; i++) {
		    receiverAddrs[i] = new InternetAddress(address[i]);
		    messgae.addRecipient(Message.RecipientType.TO, new InternetAddress(address[i]));
		}
		Transport tran = session.getTransport();
		tran.connect(SENDER_HOST, SENDER_PORT, SENDER_ADDR, SENDER_PASSWORD); // 连接到邮箱服务器
		tran.sendMessage(messgae, receiverAddrs); // 设置邮件接收人
		tran.close();
    }
    
	public static void main(String[] args) throws MessagingException, IOException {
		sendMail("测试发送", "abcdefg", "fye@xinchao.com");
		System.out.println("success");
	}
}
